#!/usr/bin/env python
from PyQt5.QtCore import pyqtSlot,pyqtProperty, pyqtSignal, QPointF, QUrl
from PyQt5.QtGui import QColor, QGuiApplication
from PyQt5.QtQml import qmlRegisterType
from PyQt5.QtQuick import (QQuickItem, QQuickView, QSGFlatColorMaterial,
        QSGGeometry, QSGGeometryNode, QSGNode)
from PyQt5.QtWidgets import QApplication,QFileDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSettings
from PyQt5.QtQml import QQmlApplicationEngine
import sys
import platform
import os
import config_json
from pathlib import Path
import traceback
import logging
import bpptablecolumn
import bpptablecolumnlist
import bpptableheading
import bpptablemodel
import BppTable_rc
from logging.handlers import RotatingFileHandler
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
sys.stderr = open(sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1)
handlers=[RotatingFileHandler(filename="report.log", maxBytes=10*1024*1024, encoding='utf-8',backupCount=3),logging.StreamHandler(sys.stdout)]
logging.basicConfig(level=logging.DEBUG,
                    format = '%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
                    handlers=handlers)
logging.info('begin')
class BezierCurve(QQuickItem):
    p1Changed = pyqtSignal(QPointF)
    @pyqtSlot(str,result=str)
    def gettime(self,format):
        curr_time = time.strftime("%H:%M:%S", time.localtime())
        return curr_time
    @pyqtSlot(str)
    def set_text_msg(self, msg):
        # 获取qml中的Text对象
        child = self.obj.findChild(QQuickItem, "text1")
        # 获取对象属性
        p = child.property("text")
        # 设置对象属性
        child.setProperty("text", p + msg)
    @pyqtProperty(QPointF, notify=p1Changed)
    def p1(self):
        return self._p1

    @p1.setter
    def p1(self, p):
        if self._p1 != p:
            self._p1 = QPointF(p)
            self.p1Changed.emit(p)
            self.update()

    p2Changed = pyqtSignal(QPointF)

    @pyqtProperty(QPointF, notify=p2Changed)
    def p2(self):
        return self._p2

    @p2.setter
    def p2(self, p):
        if self._p2 != p:
            self._p2 = QPointF(p)
            self.p2Changed.emit(p)
            self.update()

    p3Changed = pyqtSignal(QPointF)

    @pyqtProperty(QPointF, notify=p3Changed)
    def p3(self):
        return self._p3

    @p3.setter
    def p3(self, p):
        if self._p3 != p:
            self._p3 = QPointF(p)
            self.p3Changed.emit(p)
            self.update()

    p4Changed = pyqtSignal(QPointF)

    @pyqtProperty(QPointF, notify=p4Changed)
    def p4(self):
        return self._p4

    @p4.setter
    def p4(self, p):
        if self._p4 != p:
            self._p4 = QPointF(p)
            self.p4Changed.emit(p)
            self.update()

    segmentCountChanged = pyqtSignal(int)

    @pyqtProperty(int, notify=segmentCountChanged)
    def segmentCount(self):
        return self._segmentCount

    @segmentCount.setter
    def segmentCount(self, count):
        if self._segmentCount != count:
            self._segmentCount = count
            self.segmentCountChanged.emit(count)
            self.update()

    def __init__(self, parent=None):
        super(BezierCurve, self).__init__(parent)

        self._p1 = QPointF(0, 0)
        self._p2 = QPointF(1, 0)
        self._p3 = QPointF(0, 1)
        self._p4 = QPointF(1, 1)

        self._segmentCount = 32

        self._root_node = None

        self.setFlag(QQuickItem.ItemHasContents, True)

    def updatePaintNode(self, oldNode, nodeData):
        if self._root_node is None:
            self._root_node = QSGGeometryNode()

            geometry = QSGGeometry(QSGGeometry.defaultAttributes_Point2D(),
                    self._segmentCount)
            geometry.setLineWidth(2)
            geometry.setDrawingMode(QSGGeometry.GL_LINE_STRIP)
            self._root_node.setGeometry(geometry)
            self._root_node.setFlag(QSGNode.OwnsGeometry)

            material = QSGFlatColorMaterial()
            material.setColor(QColor(255, 0, 0))
            self._root_node.setMaterial(material)
            self._root_node.setFlag(QSGNode.OwnsMaterial)
        else:
            geometry = self._root_node.geometry()
            geometry.allocate(self._segmentCount)

        w = self.width()
        h = self.height()
        vertices = geometry.vertexDataAsPoint2D()

        for i in range(self._segmentCount):
            t = i / float(self._segmentCount - 1)
            invt = 1 - t

            pos = invt * invt * invt * self._p1 \
                    + 3 * invt * invt * t * self._p2 \
                    + 3 * invt * t * t * self._p3 \
                    + t * t * t * self._p4

            vertices[i].set(pos.x() * w, pos.y() * h)

        self._root_node.markDirty(QSGNode.DirtyGeometry)

        return self._root_node

def main0():
    if platform.uname().system=="Windows":
        pass
    else:
        from Watcher import Watcher
        Watcher()
    QApplication.setApplicationName("装箱单")
    QApplication.setOrganizationName("QtProject")

    app = QApplication(sys.argv)
    # print(dir(app))
    QIcon.setThemeName("gallery")

    settings = QSettings()
    # if not os.environ.get("QT_QUICK_CONTROLS_STYLE"):
    #     style_name = settings.value("style")
    #     if style_name:
    #         QQuickStyle.setStyle(style_name)
    # QQuickStyle.setStyle("Material")
    engine = QQmlApplicationEngine()
    # built_in_styles = ["Basic", "Fusion", "Imagine", "Material", "Universal"]
    # if platform.system() == "Darwin":
    #     built_in_styles.append("macOS")
    # elif platform.system() == "Windows":
    #     built_in_styles.append("Windows")
    # engine.setInitialProperties({"builtInStyles": built_in_styles})

    # Get the path of the current directory, and then add the name
    # of the QML file, to load it.
    qmlRegisterType(BezierCurve, "CustomGeometry", 1, 0, "BezierCurve")
    qmlRegisterType(bpptablecolumn.BTColumn, "BppTable", 1, 0, "BTColumn")
    qmlRegisterType(bpptablemodel.BTModel, "BppTable", 1, 0, "BTModel")
    qmlRegisterType(bpptablecolumnlist.BTColList, "BppTable", 1, 0, "BTColList")
    # qml_file = Path(__file__).parent / 'colorgrid.qml'
    qml_file = Path(__file__).parent / 'main_arr.qml'
    # qml_file = Path(__file__).parent / 'main_wbutton.qml'
    # qml_file = Path(__file__).parent / 'main_multiselect.qml'
    # qml_file = Path(__file__).parent / 'main_date.qml'
    # qml_file = Path(__file__).parent / 'main_simple.qml'
    # qml_file = Path(__file__).parent / 'C1.qml'
    engine.load(str(qml_file))

    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec())
# def main1():
#     app = QGuiApplication(sys.argv)

#     qmlRegisterType(BezierCurve, "CustomGeometry", 1, 0, "BezierCurve")

#     view = QQuickView()
#     format = view.format()
#     format.setSamples(16)
#     view.setFormat(format)

#     view.setSource(QUrl('main.qml'))
#     view.show()

#     sys.exit(app.exec_())
if __name__ == '__main__':
    config_json.read_setting()
    main0()
